package com.sqx.modules.health.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.modules.health.entity.AppCustoms;
import com.sqx.modules.health.entity.Record;
import com.sqx.modules.health.service.*;
import com.sqx.modules.health.utils.DateUtil;
import com.sqx.modules.health.utils.StringUtil;
import com.sqx.modules.health.utils.TaiyiUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Formatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gxy
 * @since 2022-06-22
 */
@Service
public class AppPatientServiceImpl implements IAppPatientService {

    @Autowired
    private IRecordService recordService;

    @Autowired
    private IAppCustomsService customsService;
    public final List<String> datas = new ArrayList<>();

    final int days =-100;

    /**
     *  血糖统计数据
     * @param jsonObject  原始数据
     * @return returnJson 统计数据
     */
    @Override
    public JSONObject getSuggerData(JSONObject jsonObject) {
        String uid = (String) jsonObject.get("uid");
        Date now = new Date();
        String endDate = DateUtil.parseStr(now,DateUtil.FMT_YYYYMMDD_HHMMSS);
        String startDate =  DateUtil.parseStr(DateUtil.addDays(now,days),DateUtil.FMT_YYYYMMDD_HHMMSS);
        QueryWrapper<Record> rm = new QueryWrapper<Record>()
                .eq("uid", jsonObject.get("uid"))
                .eq("type",jsonObject.get("type"))
                .eq("flag", 1) // 黄劲博
                //.between("recordtime",DateUtil.addDays(new Date(),days),new Date()) //需求未明确，先查询30天数据
                .orderByDesc("recordtime");
        List<Record> glucoseList= recordService.list(rm);
        List<Record> beforeDatas=new ArrayList<Record>();
        List<Record> afterDatas=new ArrayList<Record>();

        //饮食习惯
        buildCustoms(uid);
        if(glucoseList!=null && glucoseList.size()>0){
            //餐前时段
            beforeDatas = glucoseList.stream().filter(one ->DateUtil.checkNearLocalDate(one.getRecordtime(),datas).contains("before")
            ).collect(Collectors.toList());

            //餐后餐后时段
            afterDatas = glucoseList.stream().filter(one ->DateUtil.checkNearLocalDate(one.getRecordtime(),datas).contains("after"))
                    .collect(Collectors.toList());



            JSONObject returnJson = new JSONObject();
//        returnJson.put("uid",jsonObject.get("uid"));
//        returnJson.put("one",calculatePat(glucoseList));//环图，表格
//        returnJson.put("two",calculatePat(beforeDatas));//餐前
//        returnJson.put("three",calculatePat(afterDatas));//餐后

            returnJson.put("uid",jsonObject.get("uid"));
            returnJson.put("data1",calculatePat(glucoseList,"glucose"));//环图，表格
            returnJson.put("total1",glucoseList.size());//环图，表格

            returnJson.put("data2",calculatePat(beforeDatas,"glucose"));//餐前
            returnJson.put("total2",beforeDatas.size());;//餐前

            returnJson.put("data3",calculatePat(afterDatas,"glucose"));//餐后
            returnJson.put("total3",afterDatas.size());;//餐后

            return returnJson;
        } else {
            JSONObject returnJson = new JSONObject();
            returnJson.put("uid",jsonObject.get("uid"));
            returnJson.put("data1",calculatePat(new ArrayList<>(),"glucose"));//环图，表格
            returnJson.put("total1",0);//环图，表格

            returnJson.put("data2",calculatePat(new ArrayList<>(),"glucose"));//餐前
            returnJson.put("total2",0);;//餐前

            returnJson.put("data3",calculatePat(new ArrayList<>(),"glucose"));//餐后
            returnJson.put("total3",0);;//餐后
            return returnJson;
        }
    }

    @Override
    public JSONObject getSuggertrend(List<Record> allList) {
        JSONObject re = new JSONObject();
        re.put("series", calculatePat2(allList));
        return re;
    }


    /**
     *  血糖基础数据
     * @param jsonObject  原始数据
     * @return returnJson 统计数据
     */
    @Override
    public JSONArray getSuggerTable(JSONObject jsonObject) {
        //view返回显示
        JSONArray display = new JSONArray();
        String uid = (String) jsonObject.get("uid");
        Date now = new Date();
        String endDate = DateUtil.parseStr(now,DateUtil.FMT_YYYYMMDD_HHMMSS);
        String startDate =  DateUtil.parseStr(DateUtil.addDays(now,days),DateUtil.FMT_YYYYMMDD_HHMMSS);
        QueryWrapper<Record> rm = new QueryWrapper<Record>()
                .eq("uid", uid)
                .eq("type",jsonObject.get("type"))
                .eq("flag", 1) // 黄劲博
                //.between("recordtime",startDate,endDate) //需求未明确，先查询30天数据
                .orderByDesc("recordtime");
        List<Record> glucoseList= recordService.list(rm);
        //获取用餐习惯
        buildCustoms(uid);
        if(glucoseList!=null && glucoseList.size()>0){
            for(int i=0; i<glucoseList.size(); i++){
                JSONObject one = new JSONObject();
                Record record= glucoseList.get(i);
                //测量时间
                one.put("pdtime",record.getRecordtime().substring(5,10).replace("-","/"));//日期2022-07-14 19:34:44
                one.put("glucose",record.getGlucose());//数值
                one.put("level",checkLevel(record.getGlucose().doubleValue()));//高还是低 3高、2正常、1低
                //位置就在
                one.put("index",DateUtil.checkNearLocalDate(record.getRecordtime(),datas).substring(0,1));//位置 1before，2after,3before，4after,5before，6after
                display.add(one);
            }
            return display;
        } else {
            return display;
        }


    }

    /**
     * 血压总览视图数据
     * @param jsonObject
     * @return
     */
    @Override
    public JSONObject getPressureData(JSONObject jsonObject) {
        String uid = (String) jsonObject.get("uid");
        Date now = new Date();
        String endDate = DateUtil.parseStr(now,DateUtil.FMT_YYYYMMDD_HHMMSS);
        String startDate =  DateUtil.parseStr(DateUtil.addDays(now,days),DateUtil.FMT_YYYYMMDD_HHMMSS);
        QueryWrapper<Record> rm = new QueryWrapper<Record>()
                .eq("uid", jsonObject.get("uid"))
                .eq("type", jsonObject.get("type"))
                .eq("flag", 1) // 黄劲博
                //.between("recordtime",startDate,endDate) //需求未明确，先查询30天数据 总览不要
                .orderByDesc("recordtime");
        List<Record> glucoseList= recordService.list(rm);
        if(glucoseList!=null && glucoseList.size()>0){
            JSONObject returnJson = new JSONObject();
            returnJson.put("uid",jsonObject.get("uid"));
            returnJson.put("total",glucoseList.size());
            returnJson.put("one",calculatePat(glucoseList,"pressure"));//环图，表格
            returnJson.put("three",calculatePressure(glucoseList));//  确定使用哪个表
            return returnJson;
        } else {
            JSONObject returnJson = new JSONObject();
            returnJson.put("uid",jsonObject.get("uid"));
            returnJson.put("total",0);
            returnJson.put("one",calculatePat(new ArrayList<Record>(),"pressure"));//环图，表格
            returnJson.put("three",calculatePressure(new ArrayList<Record>()));//  确定使用哪个表
            return returnJson;
        }
    }

    /**
     * 血压趋势数据
     * @return
     */
    @Override
    public JSONObject getPressuretrend(List<Record> allList) {
        JSONObject re = new JSONObject();
        re.put( "pressureTrend",calculatePressureTrand(allList));
        return re;
    }
    /**
     * 血压基础数据
     * @param jsonObject
     * @return
     */
    @Override
    public JSONObject getPressureTable(JSONObject jsonObject) {
        String uid = (String) jsonObject.get("uid");
        Date now = new Date();
        String endDate = DateUtil.parseStr(now,DateUtil.FMT_YYYYMMDD_HHMMSS);
        String startDate =  DateUtil.parseStr(DateUtil.addDays(now,days),DateUtil.FMT_YYYYMMDD_HHMMSS);
        QueryWrapper<Record> rm = new QueryWrapper<Record>()
                .eq("uid", uid)
                .eq("type", jsonObject.get("type"))
                //.between("recordtime",startDate,endDate) //需求未明确，先查询30天数据
//                .ge("recordtime",startDate)
//                .le("recordtime",endDate)
                .orderByDesc("recordtime");
        List<Record> glucoseList= recordService.list(rm);
        //view返回显示
        JSONObject display = new JSONObject();
        if(glucoseList!=null && glucoseList.size()>0){
            for(int i=0; i<glucoseList.size(); i++){
                JSONObject one = new JSONObject();
                Record record= glucoseList.get(i);
                //测量时间
                one.put("pdtime",record.getRecordtime());//日期
                one.put("glucose",record.getGlucose());//数值
                one.put("sys",record.getSys());//数值
                one.put("dia",record.getDia());//数值
                one.put("pul",record.getPul());//数值
                display.put((i+1)+"",one);
            }
        } else {
            return display;
        }

        return display;
    }


    public JSONObject buildTable(List<Record> totleList) {
        JSONObject jsonObject = new JSONObject();

        if(totleList.size()==0){
            jsonObject.put("total",0);
            jsonObject.put("lNum",0);
            jsonObject.put("mNum",0);
            jsonObject.put("hNum",0);
            jsonObject.put("lRate",0);
            jsonObject.put("mRate",0);
            jsonObject.put("hRate",0);
            return jsonObject;
        }

        List<Record> lowList = totleList.stream().filter(record -> record.getSys().doubleValue()<6999
        ).collect(Collectors.toList());

        List<Record> midList = totleList.stream().filter(record -> (19<=record.getSys().doubleValue()&&record.getGlucose().doubleValue()<=24)
        ).collect(Collectors.toList());

        List<Record> heightList = totleList.stream().filter(record -> record.getSys().doubleValue()>6999
        ).collect(Collectors.toList());

        jsonObject.put("total",totleList.size());
        jsonObject.put("lNum",lowList.size());
        jsonObject.put("mNum",midList.size());
        jsonObject.put("hNum",heightList.size());

        Double lRate =0D,nRate=0D,hRate=0D;
        lRate= Double.valueOf(lowList.size()/totleList.size());
        nRate= Double.valueOf(midList.size()/totleList.size());
        hRate= Double.valueOf(heightList.size()/totleList.size());

        jsonObject.put("lRate",format4(lRate));
        jsonObject.put("mRate",format4(nRate));
        jsonObject.put("hRate",format4(hRate));
        return  jsonObject;
    }

    /**
     * 获取用餐习惯
     * @param uid 用户id
     * @return 写入缓存数据
     */
    public void buildCustoms(String uid){
        datas.clear();
        //取标准
        QueryWrapper<AppCustoms> rmCustoms = new QueryWrapper<AppCustoms>()
                .eq("uid", uid);
        AppCustoms customs = customsService.getOne(rmCustoms);
        if(customs==null){
            datas.add("05:00-08:00-1before");
            datas.add("08:00-10:00-2after");
            datas.add("10:00-12:00-3before");
            datas.add("12:00-15:00-4after");
            datas.add("15:00-18:00-5before");
            datas.add("18:00-20:00-6after");
            datas.add("20:00-24:00-7before");
            datas.add("00:00-05:00-8after");
        } else {
            datas.add(customs.getBreakfaststartdate().concat("-1before"));
            datas.add(customs.getBreakfastenddate().concat("-2after"));
            datas.add(customs.getLunchstartdate().concat("-3before"));
            datas.add(customs.getLunchenddate().concat("-4after"));
            datas.add(customs.getDinnerstartdate().concat("-5before"));
            datas.add(customs.getDinnerenddate().concat("-6after"));
            datas.add(customs.getSleepstart().concat("-7before"));
            datas.add(customs.getSleepend().concat("-8after"));
        }

//        datas.add(customs.getT1().concat("-9before"));
//        datas.add(customs.getT2().concat("-10after"));

    }

    /**
     * 血糖统计信息计算函数
     *
     * @param val   数值
     * @return  3-高，2-正常，1-低
     */
    public static int checkLevel(Double val) {
        int hight=7; int low=4;
        if(val>hight)return 3;
        if(hight>val && val>low)return 2;
        if(val<=low)return 1;
        return  0;
    }

    /**
     * 血糖统计信息计算函数
     *
     * @param totleList
     */
    public JSONArray calculatePat(List<Record> totleList,String type) {
        JSONObject jsonObject = new JSONObject();
        JSONArray  retrun = new JSONArray();
        if(totleList.size()==0){
            JSONObject low = new JSONObject();
            low.put("name","偏低");
            low.put("value",0);
            low.put("ratio",0);
            JSONObject mid = new JSONObject();
            mid.put("name","正常");
            mid.put("value",0);
            mid.put("ratio",0);
            JSONObject hight = new JSONObject();
            hight.put("name","偏高");
            hight.put("value",0);
            hight.put("ratio",0);
            retrun.add(low);
            retrun.add(mid);
            retrun.add(hight);
            return retrun;
        }

        List<Record> lowList = new ArrayList<>();
        List<Record> midList = new ArrayList<>();
        List<Record> heightList = new ArrayList<>();
        if(type.equals("glucose")){
            lowList = totleList.stream().filter(record -> record.getGlucose().doubleValue()<6
            ).collect(Collectors.toList());
            midList = totleList.stream().filter(record -> (6<=record.getGlucose().doubleValue()&&record.getGlucose().doubleValue()<=8)
            ).collect(Collectors.toList());
            heightList = totleList.stream().filter(record -> record.getGlucose().doubleValue()>8
            ).collect(Collectors.toList());
        }
        if(type.equals("pressure")){
            lowList = totleList.stream().filter(record -> record.getSys().doubleValue()<80
            ).collect(Collectors.toList());
            midList = totleList.stream().filter(record -> (80<=record.getSys().doubleValue()&&record.getSys().doubleValue()<=135)
            ).collect(Collectors.toList());
            heightList = totleList.stream().filter(record -> record.getSys().doubleValue()>140
            ).collect(Collectors.toList());
        }
        jsonObject.put("total",totleList.size());
        jsonObject.put("lNum",lowList.size());
        jsonObject.put("mNum",midList.size());
        jsonObject.put("hNum",heightList.size());

        String lRate ="",nRate="",hRate="";
        lRate= TaiyiUtil.percentInstance(lowList.size(),totleList.size());
        nRate= TaiyiUtil.percentInstance(midList.size(),totleList.size());
        hRate= TaiyiUtil.percentInstance(heightList.size(),totleList.size());

        jsonObject.put("lRate",lRate);
        jsonObject.put("nRate",nRate);
        jsonObject.put("hRate",hRate);
        jsonObject.put("data",totleList);//全部数据加上，如有必要

        JSONObject low = new JSONObject();
        low.put("name","偏低");
        low.put("value",lowList.size());
        low.put("ratio",lRate);
        JSONObject mid = new JSONObject();
        mid.put("name","正常");
        mid.put("value",midList.size());
        mid.put("ratio",nRate);
        JSONObject hight = new JSONObject();
        hight.put("name","偏高");
        hight.put("value",heightList.size());
        hight.put("ratio",hRate);

        retrun.add(low);
        retrun.add(mid);
        retrun.add(hight);
        return  retrun;
    }
    /**
     * 血糖统计趋势信息计算函数
     *
     * @param totleList
     */
    public JSONArray calculatePat2(List<Record> totleList) {
        JSONArray  retrun = new JSONArray();
        if(totleList.size()==0){
            JSONObject low = new JSONObject();
            JSONArray datalow = new JSONArray();
            low.put("name","偏低");
            low.put("data",datalow);
            JSONObject mid = new JSONObject();
            JSONArray datamid = new JSONArray();
            mid.put("name","正常");
            mid.put("data",datamid);
            JSONObject hight = new JSONObject();
            JSONArray datahight = new JSONArray();
            hight.put("name","偏高");
            hight.put("data",datahight);
            retrun.add(low);
            retrun.add(mid);
            retrun.add(hight);
            return retrun;
        }

        final List indexList = new ArrayList();
        List indexLow = new ArrayList<Integer>();
        List indexMid = new ArrayList<Integer>();
        List indexHig = new ArrayList<Integer>();
        indexList.add(indexLow);
        indexList.add(indexMid);
        indexList.add(indexHig);
        final Integer[] index = new Integer[]{0,0,0};
        //偏低
        List<Record> lowList = totleList.stream().filter(record -> {
                    index[0] += 1;
                    if (record.getGlucose().doubleValue()<6){
                        ((ArrayList<Integer>) (indexList.get(0))).add(index[0]);
                    }
                    return record.getGlucose().doubleValue()<6;
                }
        ).collect(Collectors.toList());

        List<Record> midList = totleList.stream().filter(record ->{
                    index[1] += 1;
                    if (6<=record.getGlucose().doubleValue()&&record.getGlucose().doubleValue()<=8){
                        ((ArrayList<Integer>) (indexList.get(1))).add(index[1]);
                    }
                    return (6<=record.getGlucose().doubleValue()&&record.getGlucose().doubleValue()<=8);
                }
        ).collect(Collectors.toList());

        //偏高
        List<Record> heightList = totleList.stream().filter(record ->{
                    index[2] += 1;
                    if (record.getGlucose().doubleValue()>8){
                        ((ArrayList<Integer>) (indexList.get(2))).add(index[2]);
                    }
                    return (record.getGlucose().doubleValue()>8);
                }
        ).collect(Collectors.toList());

        JSONObject low = new JSONObject();
        JSONArray datalow = new JSONArray();
        low.put("name","偏低");

        for(int i=0;i<lowList.size();i++){
            JSONArray onel = new JSONArray();

            onel.add(((ArrayList<Integer>) (indexList.get(0))).get(i));
            onel.add(lowList.get(i).getGlucose());
            datalow.add(onel);
        }
        low.put("data",datalow);


        JSONObject mid = new JSONObject();
        JSONArray datamid = new JSONArray();
        mid.put("name","正常");
        for(int i=0;i<midList.size();i++){
            JSONArray onem = new JSONArray();

            onem.add(((ArrayList<Integer>) (indexList.get(1))).get(i));
            onem.add(midList.get(i).getGlucose());
            datamid.add(onem);
        }
        mid.put("data",datamid);


        JSONObject hight = new JSONObject();
        JSONArray datahight = new JSONArray();
        hight.put("name","偏高");
        for(int i=0;i<heightList.size();i++){
            JSONArray oneh = new JSONArray();
            oneh.add(((ArrayList<Integer>) (indexList.get(2))).get(i));
            oneh.add(heightList.get(i).getGlucose());
            datahight.add(oneh);
        }
        hight.put("data",datahight);

        retrun.add(low);
        retrun.add(mid);
        retrun.add(hight);
        return  retrun;
    }
    /**
     * 统计血压信息
     *
     * @param list
     */
    public JSONArray calculatePressureTrand(List<Record> list) {
        JSONArray jsonObject = new JSONArray();
        //收缩压
        List<Record> newSysList = list.stream().filter(record -> record.getSys()!=null).collect(Collectors.toList());
        JSONObject tSys = new JSONObject();
        tSys.put("name","收缩压");
        JSONArray oneh = new JSONArray();
        for(int i=0;i<newSysList.size();i++){
            oneh.add(newSysList.get(i).getSys());
        }
        tSys.put("data",oneh);

        //舒张压
        List<Record> newDiaList = list.stream().filter(record -> record.getDia()!=null).collect(Collectors.toList());
        JSONObject tDia = new JSONObject();
        tDia.put("name","舒张压");
        JSONArray oneDia = new JSONArray();
        for(int i=0;i<newDiaList.size();i++){
            oneDia.add(newDiaList.get(i).getDia());
        }
        tDia.put("data",oneDia);

        //心率
        List<Record> newPulList = list.stream().filter(record -> record.getPul()!=null).collect(Collectors.toList());
        JSONObject tPul = new JSONObject();
        tPul.put("name","心率");
        JSONArray onetPul = new JSONArray();
        for(int i=0;i<newPulList.size();i++){
            onetPul.add(newPulList.get(i).getPul());
        }
        tPul.put("data",onetPul);

        jsonObject.add(tSys);
        jsonObject.add(tDia);
        jsonObject.add(tPul);
        return jsonObject;
    }
    /**
     * 统计血压信息
     *
     * @param list
     */
    public JSONArray calculatePressure(List<Record> list) {

        if(list.size()==0){
            JSONArray sone = new JSONArray();
            sone.add("收缩压");
            sone.add("");
            sone.add("");
            sone.add("");
            JSONArray done = new JSONArray();
            done.add("舒张压");
            done.add("");
            done.add("");
            done.add("");
            JSONArray pone = new JSONArray();
            pone.add("心率");
            pone.add("");
            pone.add("");
            pone.add("");
            JSONArray total = new JSONArray();
            total.add(sone);
            total.add(done);
            total.add(pone);

            return total;
        }

        //收缩压 最大 最小
        List<Record> newSysList = list.stream().filter(record -> record.getSys()!=null).collect(Collectors.toList());
        //最小值
        Integer minSys = newSysList.stream().mapToInt(Record::getSys).min().getAsInt();
        //最大值
        Integer maxSys = newSysList.stream().mapToInt(Record::getSys).max().getAsInt();
        //平均值
        Double averageSys = newSysList.stream().mapToInt(Record::getSys).average().getAsDouble();
//        ruturnList.add(maxSys);
//        ruturnList.add(minSys);
//        ruturnList.add(format4(averageSys));
        //ruturnList.add(standSysAvg);
//        jsonObject.put("maxSys",maxSys);
//        jsonObject.put("minSys",minSys);
//        jsonObject.put("averageSys",format4(averageSys));
        //舒张压 最大 最小
        List<Record> newDiaList = list.stream().filter(record -> record.getDia()!=null).collect(Collectors.toList());
        //最小值
        Integer minDia = newDiaList.stream().mapToInt(Record::getDia).min().getAsInt();
        //最大值
        Integer maxDia = newDiaList.stream().mapToInt(Record::getDia).max().getAsInt();
        //平均值
        Double averageDia = newDiaList.stream().mapToInt(Record::getDia).average().getAsDouble();
//        ruturnList.add(maxDia);
//        ruturnList.add(minDia);
//        ruturnList.add(format4(averageDia));
        //ruturnList.add(standDiaAvg);
//        jsonObject.put("maxDia",maxDia);
//        jsonObject.put("minDia",minDia);
//        jsonObject.put("averageDia",format4(averageDia));
        //心率 最大 最小
        List<Record> newPulList = list.stream().filter(record -> record.getPul()!=null).collect(Collectors.toList());
        //最小值
        Integer minPul = newPulList.stream().mapToInt(Record::getPul).min().getAsInt();
        //最大值
        Integer maxPul = newPulList.stream().mapToInt(Record::getPul).max().getAsInt();
        //平均值
        Double averagePul = newPulList.stream().mapToInt(Record::getPul).average().getAsDouble();
//        ruturnList.add(maxPul);
//        ruturnList.add(minPul);
//        ruturnList.add(format4(averagePul));
        //ruturnList.add(standPulAvg);
//        jsonObject.put("maxPul",maxPul);
//        jsonObject.put("minPul",minPul);
//        jsonObject.put("averagePul",format4(averagePul));
        //ruturnList.add(sysWaring);
        //ruturnList.add(diaWaring);
        JSONArray sone = new JSONArray();
        sone.add("收缩压");
        sone.add(maxSys);
        sone.add(minSys);
        sone.add(format4(averageSys));
        JSONArray done = new JSONArray();
        done.add("舒张压");
        done.add(maxDia);
        done.add(minDia);
        done.add(format4(averageDia));
        JSONArray pone = new JSONArray();
        pone.add("心率");
        pone.add(maxPul);
        pone.add(minPul);
        pone.add(format4(averagePul));
        JSONArray total = new JSONArray();
        total.add(sone);
        total.add(done);
        total.add(pone);


        return total;
    }
    /**
     * %.2f % 表示 小数点前任意位数 2 表示两位小数 格式后的结果为 f 表示浮点型
     */
    public static String format4(double value) {
        return new Formatter().format("%.2f", value).toString();
    }

    @Override
    public JSONObject getChartDataJSONObject(List<Record> allList, String type, String startDate, String endDate) {
        JSONObject result = new JSONObject();
        // 获取x轴
        List<String> daysStringList = new ArrayList<>();
        try {
            daysStringList = DateUtil.getDaysStringBetweenDates(startDate, endDate);
            result.put("categories", daysStringList);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        JSONArray categories = new JSONArray();
        if (allList.size() == 0) {
            result.put("series", categories);
            //result.put("currDayData", currDayData);
            return result;
        }
        JSONObject currDayData = new JSONObject();
        currDayData.put("currDayDate", endDate.replace("-", "/").substring(6));
        currDayData.put("currDayVal", "--");

        // 血糖
        if ("1".equals(type)) {
            //饮食习惯
            //buildCustoms(uid);
            // 6-8 正常
            //result.put("status", glucose.doubleValue() < 6 ? "偏低" : glucose.doubleValue() > 8 ? "偏高" : "正常");
            JSONObject item = new JSONObject();
            item.put("name", "血糖");
            JSONArray data = new JSONArray();
            for (int i = 0; i < daysStringList.size(); i++) {
                String dateStr = daysStringList.get(i).replace('/', '-');
                boolean valuable = true;
                for (Record record : allList) {
                    if (i == daysStringList.size() -1) {
                        currDayData.put("currDayVal", record.getGlucose());
                    }
                    String recordtime = record.getRecordtime();
                    if (record.getRecordtime().contains(dateStr)) {
                        valuable = false;
                        data.add(record.getGlucose());
                        break;
                    }
                }
                if (valuable) {
                    data.add(0);
                }
            }
            item.put("data", data);
            categories.add(item);
        }

        // 2 血压
        if ("2".equals(type)) {
            // 收缩压 sys 舒张压 dia 脉搏 pul
            JSONArray sysData = new JSONArray();
            JSONArray diaData = new JSONArray();
            JSONArray pulData = new JSONArray();
            for (String s : daysStringList) {
                String dateStr = s.replace('/', '-');
                boolean valuable = true;
                for (Record record : allList) {
                    if (s.equals(daysStringList.get(daysStringList.size() - 1))) {
                        currDayData.put("currDayVal", record.getSys());
                    }
                    if (record.getRecordtime().contains(dateStr)) {
                        valuable = false;
                        sysData.add(record.getSys());
                        diaData.add(record.getDia());
                        pulData.add(record.getPul());
                        break;
                    }
                }
                if (valuable) {
                    sysData.add(0);
                    diaData.add(0);
                    pulData.add(0);
                }
            }
            JSONObject sysItem = new JSONObject();
            JSONObject diaItem = new JSONObject();
            JSONObject pulItem = new JSONObject();
            sysItem.put("name", "收缩压");
            diaItem.put("name", "舒张压");
            pulItem.put("name", "心率");
            sysItem.put("data", sysData);
            diaItem.put("data", diaData);
            pulItem.put("data", pulData);
            categories.add(sysItem);
            categories.add(diaItem);
            categories.add(pulItem);
        }

        // 8 血脂
        if ("8".equals(type)) {
            // 总胆固醇 tcho 甘油三酯 tg 低密度脂蛋白胆固醇 ldl 高密度脂蛋白胆固醇 hdl
            JSONArray tchoData = new JSONArray();
            JSONArray tgData = new JSONArray();
            JSONArray ldlData = new JSONArray();
            JSONArray hdlData = new JSONArray();
            for (String s : daysStringList) {
                String dateStr = s.replace('/', '-');
                boolean valuable = true;
                for (Record record : allList) {
                    if (s.equals(daysStringList.get(daysStringList.size() - 1))) {
                        currDayData.put("currDayVal", record.getTcho());
                    }
                    if (record.getRecordtime().contains(dateStr)) {
                        valuable = false;
                        tchoData.add(record.getTcho());
                        tgData.add(record.getTg());
                        ldlData.add(record.getLdl());
                        hdlData.add(record.getHdl());
                        break;
                    }
                }
                if (valuable) {
                    tchoData.add(0);
                    tgData.add(0);
                    ldlData.add(0);
                    hdlData.add(0);
                }
            }
            JSONObject tchoItem = new JSONObject();
            JSONObject tgItem = new JSONObject();
            JSONObject ldlItem = new JSONObject();
            JSONObject hdlItem = new JSONObject();
            tchoItem.put("name", "总胆固醇");
            tgItem.put("name", "甘油三酯");
            ldlItem.put("name", "低密度脂蛋白胆固醇");
            hdlItem.put("name", "低密度脂蛋白胆固醇");
            tchoItem.put("data", tchoData);
            tgItem.put("data", tgData);
            ldlItem.put("data", ldlData);
            hdlItem.put("data", hdlData);
            categories.add(tchoItem);
            categories.add(tgItem);
            categories.add(ldlItem);
            categories.add(hdlItem);
        }

        // 6 尿酸
        if ("6".equals(type)) {
            // 6-8 正常
            //result.put("status", glucose.doubleValue() < 6 ? "偏低" : glucose.doubleValue() > 8 ? "偏高" : "正常");
            JSONObject item = new JSONObject();
            item.put("name", "尿酸");
            JSONArray data = new JSONArray();
            for (String s : daysStringList) {
                String dateStr = s.replace('/', '-');
                boolean valuable = true;
                for (Record record : allList) {
                    if (s.equals(daysStringList.get(daysStringList.size() - 1))) {
                        currDayData.put("currDayVal", record.getUric());
                    }
                    if (record.getRecordtime().contains(dateStr)) {
                        valuable = false;
                        data.add(record.getUric());
                        break;
                    }
                }
                if (valuable) {
                    data.add(0);
                }
            }
            item.put("data", data);
            categories.add(item);
        }

        result.put("series", categories);
        result.put("currDayData", currDayData);

        return result;
    }

}
